from typing import *


class Solution:

    def findCircleNum(self, isConnected: List[List[int]]) -> int:

        class UnionFind():

            def __init__(self, size: int) -> None:
                self.p = [i for i in range(size)]
                self.cnts = [1] * size
                self.size = size

            def find(self, a):
                if self.p[a] != a:
                    self.p[a] = self.find(self.p[a])
                return self.p[a]

            def union(self, a: int, b: int):
                A, B = self.find(a), self.find(b)
                if A != B:
                    self.p[B] = A
                    self.cnts[A] += self.cnts[B]
                    self.cnts[B] = 0
                    self.size -= 1

            def isSameSet(self, a: int, b: int) -> bool:
                return self.find(a) == self.find(b)

        n = len(isConnected)
        uf = UnionFind(n)
        for i in range(n):
            for j in range(i, n):
                if isConnected[i][j] == 1:
                    uf.union(i, j)
        return uf.size